<template>
    <div>
        <div :class="$style.color">
            <div :class="$style.textContent">
                <p v-for="(item, index) of productinfos"
                    :key="index">{{item}}</p>
            </div>
            <textarea :class="$style.textarea"
                placeholder="请输入内容..."
                autofocus
                v-model="textValue" />
            </div>
        <button @click = "initWebSocket">点击聊天</button>
        <button @click = "websocketsend">发送聊天</button>
        <button @click = "websocketclose">断开连接</button>
    </div>
</template>
<script>
import Cookies from "js-cookie"
export default {
    name: "SearchCustomer",
    data() {
        return {
            productinfos: [],
            textValue: ""
        }
    },
    created() {
        this.initWebSocket()
    },
    destroyed() {
        this.websocketclose()
    },
    methods: {
        initWebSocket() {
            // 初始化weosocket
            let sessionId = Cookies.get("sessionId")
            let wsuri = "ws://192.168.2.68:8011/websocket/" + sessionId
            this.websock = new WebSocket(wsuri)
            this.websock.onmessage = this.websocketonmessage
            this.websock.onopen = this.websocketonopen
            this.websock.onerror = this.websocketonerror
            this.websock.onclose = this.websocketclose
        },
        websocketonopen() {
            console.log("连接成功")
        },
        websocketonerror(e) {
            console.log(e)
        },
        websocketonmessage(e) {
            // 数据接收
            const redata = JSON.parse(e.data)
            console.log(redata.message[0].values.text)
            if (redata.messageType === 5) {
                this.productinfos.push(redata.message[0].values.text)
                return
            }
            this.productinfos.push(redata.message)
        },
        websocketsend() {
            let sessionId = Cookies.get("sessionId")
            // 数据发送
            let obj = {
                message: this.textValue,
                token: sessionId,
                to: "Robot"
            }
            this.websock.send(JSON.stringify(obj))
        },
        websocketclose(e) {
            this.websock.close()
            console.log("断开连接", e)
        }
    }
}
</script>
<style module>
    .color {
        width: 80%;
        height: 600px;
        position: relative;
    }
    .textarea {
        width: 100%;
        height: 100px;
        resize: none;
        bottom: 0;
        outline: none;
        font-size: 18px;
        font-family: 楷体;
        position: absolute;
    }
    .textContent {
        width: 100%;
        height: 500px;
        padding-bottom: 100px;
        background: white;
        overflow: scroll;
    }
    button {
        width: 80px;
        height: 30px;
        outline: none;
        cursor: pointer;
        background: #0bdc79;
        border: 0px;
    }
</style>
